package com.cskaoyan.gateway.controller.order;


import com.cskaoyan.gateway.form.order.CreateOrderForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.*;
import com.mall.user.IUserService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import com.mall.user.dto.UsernameIdToken;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author: lsy
 * @class: OrderController
 */
// 生成日志
@Slf4j
@RestController
@RequestMapping("/shopping")
// 接口文档
@Api(tags = "OrderController", description = "购物订单控制层")
public class OrderController {

    @Reference(timeout = 30000, check = false, retries = 0)
    private OrderCoreService orderCoreService;

    @Reference(timeout = 30000, check = false, retries = 0)
    private OrderQueryService orderQueryService;

    @Reference(timeout = 30000, check = false, retries = 0)
    private IUserService userService;

    @SneakyThrows
    @ApiOperation(value = "创建订单", notes = "创建订单")
    @PostMapping("/order")
    public ResponseData createOrder(@RequestBody CreateOrderForm createOrderForm, HttpServletRequest request) {
        // 为了debug调试看参数传没传进来传没传正确
        log.debug(createOrderForm.toString());


        UsernameIdToken usernameIdToken = (UsernameIdToken) request.getAttribute(TokenIntercepter.USER_INFO_KEY);

        long userId = usernameIdToken.getUserId();


        // 设置uniqueKey
        String uniqueKey = UUID.randomUUID().toString();

        // 放到request中
        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setAddressId(createOrderForm.getAddressId());
        createOrderRequest.setCartProductDtoList(createOrderForm.getCartProductDtoList());
        createOrderRequest.setOrderTotal(createOrderForm.getOrderTotal());
        createOrderRequest.setStreetName(createOrderForm.getStreetName());
        createOrderRequest.setTel(createOrderForm.getTel());
        createOrderRequest.setUniqueKey(uniqueKey);
        createOrderRequest.setUserId(userId);
        createOrderRequest.setUserName(createOrderForm.getUserName());

        CreateOrderResponse response = orderCoreService.createOrder(createOrderRequest);

        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("delay_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
//        String orderId = response.getOrderId();
        try {
            consumer.subscribe("delay_order", "*");
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                // 取消订单的业务实现
                CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
                MessageExt messageExt = msgs.get(0);
                byte[] body = messageExt.getBody();
                String orderId = new String(body, 0, body.length, StandardCharsets.UTF_8);
                cancelOrderRequest.setOrderId(orderId);

                orderCoreService.cancelOrder(cancelOrderRequest);
                System.out.println("订单超时删除");
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        try {
            consumer.start();
        } catch (MQClientException ignored) {
        }

        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderId());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @SneakyThrows
    @ApiOperation(value = "查看订单", notes = "查看订单")
    @GetMapping("/order")
    public ResponseData queryOrder(Integer page, Integer size, String sort, HttpServletRequest httpServletRequest) {

        UsernameIdToken usernameIdToken = (UsernameIdToken) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);

        long userId = usernameIdToken.getUserId();
        OrderListRequest request = new OrderListRequest();
        request.setUserId(userId);
        request.setPage(page);
        request.setSize(size);
        request.setSort(sort);
        OrderListResponse response = orderQueryService.queryOrders(request);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("data", response.getDetailInfoList());
            hashMap.put("total", response.getTotal());
            return new ResponseUtil<>().setData(hashMap);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @SneakyThrows
    @ApiOperation(value = "查看用户一个订单", notes = "传入订单号查找订单")
    @GetMapping("/order/{id}")
    public ResponseData queryOneOrder(@PathVariable("id") String id, HttpServletRequest httpServletRequest) {

        UsernameIdToken usernameIdToken = (UsernameIdToken) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);

        long userId = usernameIdToken.getUserId();
        OrderRequest orderRequest = new OrderRequest();
        // 订单号已经可以唯一确定了，不用传userId了
        orderRequest.setOrderId(id);
        OrderResponse response = orderQueryService.queryOrder(orderRequest);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getOrderDto());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @ApiOperation ("取消订单")
    @PostMapping("/cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request){
        CancelOrderResponse response=orderCoreService.cancelOrder(request);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
            System.out.println(response);
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    @ApiOperation ("删除订单")
    @DeleteMapping("//order/{orderId}")
    public ResponseData deleteOrder(@PathVariable String orderId){
        DeleteOrderResponse response = orderCoreService.deleteOrder (orderId);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
            System.out.println(response);
            return new ResponseUtil<>().setData(response);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }
}
